<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        size="small"
        v-model="listQuery.category_idP"
        default-first-option
        style="width: 180px"
        placeholder="选择一级类别"
        clearable
        @change="change"
      >
        <el-option
          v-for="(item, index) in joinArr"
          :key="index"
          :label="item.category_name"
          :value="item.category_id"
        />
      </el-select>
      <el-select
        size="small"
        v-model="listQuery.category_idC"
        default-first-option
        style="width: 180px"
        placeholder="选择二级类别"
        clearable
      >
        <el-option
          v-for="(item, index) in joinArr1"
          :key="index"
          :label="item.category_name"
          :value="item.category_id"
        />
      </el-select>
      <el-input
        size="small"
        v-model="listQuery.plan_start_date"
        style="width: 200px"
        class="filter-item"
        placeholder="计划开始时间"
        clearable
      />
      <el-input
        size="small"
        v-model="listQuery.title"
        style="width: 200px"
        class="filter-item"
        placeholder="名称"
        clearable
      />

      <el-select
        size="small"
        v-model="listQuery.jieduan"
        default-first-option
        style="width: 180px"
        placeholder="阶段"
        clearable
      >
        <el-option
          v-for="(item, index) in jieduanArr"
          :key="index"
          :label="item.value"
          :value="item.value"
        />
      </el-select>
      <el-select
        size="small"
        v-model="listQuery.status"
        default-first-option
        style="width: 180px"
        placeholder="完成状态"
        clearable
      >
        <el-option
          v-for="(item, index) in statusArr"
          :key="index"
          :label="item.status"
          :value="item.value"
        />
      </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="edit"
        @click="showCreate"
      >
        添加
      </el-button>
    </div>
    <div class="table-container">
      <el-table
        key="tableKey"
        :data="list"
        v-loading="listLoading"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column align="center" label="编号" width="70">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="名称">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="一级分类">
          <template slot-scope="scope">
            <span>{{ scope.row.category_top_name }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="二级分类">
          <template slot-scope="scope">
            <span> {{ scope.row.category_name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="阶段">
          <template slot-scope="scope">
            <span>{{ scope.row.jieduan }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="封面图" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-image style="width: 60px;" :src="scope.row.cover" :preview-src-list="scope.row.imglist"></el-image>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="状态" width="80px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
              <span>{{ scope.row.status == 1 ? "已完成" : "未完成" }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间" width="180px">
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否推荐" width="80px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.recommend"
              active-color="#13ce66"
              :inactive-value="0"
              :active-value="1"
              inactive-color="grey"
              @change="changeRecomStatus(scope.row, scope.row.recommend)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="250px">
          <template slot-scope="scope">
            <el-button
              plain
              size="small"
              type="primary"
              @click="updateAction(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              plain
              v-if="scope.row.status == 1"
              size="small"
              type="warning"
              @click="changeStatus(scope.row, 2)"
              >未完成</el-button
            >
            <el-button
              plain
              v-else
              size="small"
              type="success"
              @click="changeStatus(scope.row, 1)"
              >已完成</el-button
            >
            <el-button
              plain
              size="small"
              type="danger"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container text-right">
      <el-pagination
        background
        :total="pagination.total"
        :current-page="listQuery.page"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="一级分类" required>
          <el-select
            size="small"
            v-model="temp.category_top_id"
            default-first-option
            style="width: 180px"
            placeholder="选择一级类别"
            clearable
            @change="change"
          >
            <el-option
              v-for="(item, index) in joinArr"
              :key="index"
              :label="item.category_name"
              :value="item.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" required>
          <el-select
            size="small"
            v-model="temp.category_id"
            default-first-option
            style="width: 180px"
            placeholder="选择二级类别"
            clearable
          >
            <el-option
              v-for="(item, index) in joinArr1"
              :key="index"
              :label="item.category_name"
              :value="item.category_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="名称" required>
          <el-input
            size="small"
            v-model="temp.title"
            maxlength="32"
            width="100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="阶段" required>
          <el-select
            size="small"
            v-model="temp.jieduan"
            default-first-option
            style="width: 180px"
            placeholder="阶段"
            clearable
          >
            <el-option
              v-for="(item, index) in jieduanArr"
              :key="index"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图" required>
          <el-upload
            class="avatar-uploader"
            :action="uploadPath"
            :headers="header"
            :show-file-list="false"
            :on-success="handleImageSuccess"
          >
            <img v-if="temp.cover" :src="temp.cover" style="width: 200px" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            :rows="2"
            size="small"
            v-model="temp.discribe"
            width="100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              v-model="temp.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              style="height: 500px; overflow-y: hidden;"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="create"
          >添 加</el-button
        >
        <el-button v-else type="primary" @click="update">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  List,
  Info,
  Create,
  Edit,
  Del,
  Status,
  recomStatus,
  ct_List,
  ct_Save,
  ct_Del,
  ct_Status,
  ct_Sort,
  ct_Plist,
  ct_Clist
} from "@/api/tixing";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/utils/common";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {}
      },
      ploadPath: uploadPath,
      list: null,
      joinArr: null,
      joinArr1: null,
      changeIndex: -1,
      pagination: {},
      dialogFormVisible: false,
      mode: "default", // or 'simple'
      recomArr: [
        { recommend: "推荐", value: 1 },
        { recommend: "不推荐", value: 0 }
      ],
      statusArr: [
        { status: "已完成", value: 1 },
        { status: "未完成", value: 0 }
      ],
      jieduanArr: [
        { value: "00" },
        { value: "11" },
        { value: "22" },
        { value: "一" },
        { value: "二" },
        { value: "三" },
        { value: "四" },
        { value: "五" },
        { value: "六" }
      ],
      temp: {
        category_name: "",
        link_url: "",
        cover: "",
        sort: 0
      },
      listQuery: {
        page: 1,
        limit: 10,
        category_name: "",
        category_id: null,
        category_idP: null,
        category_idC: null,
        status: "",
        recommend: ""
      },
      uploadPath: uploadPath,
      dialogStatus: null,
      dialogTitle: "",
      header: {
        Authorization: getToken()
      }
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  created() {
    this.getList(),
      this.getCtList(),
      (this.editorConfig.MENU_CONF["uploadImage"] = {
        server: uploadPath,
        fieldName: "file",
        // 单个文件的最大体积限制，默认为 2M
        maxFileSize: 2 * 1024 * 1024, // 2M
        // 最多可上传几个文件，默认为 100
        maxNumberOfFiles: 10,
        // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
        allowedFileTypes: ["image/*"],
        // 自定义增加 http  header
        headers: {
          Authorization: getToken()
        },
        // 跨域是否传递 cookie ，默认为 false
        withCredentials: false,
        // 超时时间，默认为 10 秒
        timeout: 5 * 1000, // 5 秒
        // 自定义插入图片
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          // 从 res 中找到 url alt href ，然后插图图片

          insertFn(res.data.filepath, "", "");
        }
      });
    this.toolbarConfig = {
      excludeKeys: ["insertVideo", "uploadVideo", "group-video"]
    };
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    getList() {
      this.listLoading = true;
      this.listQuery.category_id = this.listQuery.category_idC
        ? this.listQuery.category_idC
        : this.listQuery.category_idP;
      List(this.listQuery).then(response => {
        var data = response.data;
        this.list = data.data;
        //图片相对路径处理
        //this.list.forEach(item=>{
        //  item.image_path=process.env.VUE_APP_BASE_PIC +  item.image_path

        //})
        this.pagination = data;
        //图片放大处理，声明一个数组，遍历一遍
        this.list.forEach(e => {
          e.imglist = [];
          e.imglist.push(e.cover);
        });
      });

      this.listLoading = false;
    },
    getCtList() {
      ct_Plist(this.listQuery).then(response => {
        var data = response.data;
        this.joinArr = data;
      });
    },
    change(val) {
      // this.listQuery.category_idC = null

      this.$set(this.listQuery, "category_idC", null);

      ct_Clist({ category_id: val }).then(response => {
        var data = response.data;
        this.joinArr1 = data;
      });
    },

    updateAction(id) {
      this.dialogStatus = "edit";

      Info({ id: id }).then(res => {
        if (res.code === 0) {
          this.btn = false;
          this.temp = res.data;
          this.change(this.temp.category_top_id);

          this.dialogTitle = "编辑";
          this.dialogFormVisible = !this.dialogFormVisible;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    changeStatus(row, status) {
      Status({ id: row.id, status: status }).then(response => {
        row.status = status;
        this.getList();
        this.$message.success("操作成功！");
      });
    },

    orderHandle(row) {
      row.show = 1;
    },

    orderHandleDo(row) {
      Sort({ id: row.id, sort: row.sort }).then(response => {
        row.show = 0;
        this.getList();
        this.$message.success("操作成功！");
      });
    },

    showCreate() {
      this.temp = {
        category_id: null,
        title: "",
        link_url: "",
        cover: "",
        plan_start_date: "",
        plan_end_date: "",
        learn_state: "",
        start_date: "",

        sort: 0
      };
      this.dialogTitle = "添加";
      this.dialogStatus = "create";
      (this.dialogTitle = "添加"), (this.dialogFormVisible = true);
    },

    handleEdit(row, status) {
      this.dialogTitle = "编辑";
      this.dialogFormVisible = true;
      this.temp = row;
      this.dialogStatus = status;
    },

    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          UserDel({ id: row.id }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //console.log(row.id);
          Del({ id: row.id }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handleImageSuccess(res, file) {
      if (res.code === 0) {
        this.temp.cover = res.data.filepath;
        //图片相对路径处理
        //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
        this.temp.cover = this.temp.cover;
        // uploadPath = uploadPath.this.temp.image_path;

        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },

    changeRecomStatus(row, top) {
      const _this = this;

      recomStatus({ id: row.id, top: top }).then(response => {
        row.top = top;

        this.$message.success(response.msg);
        this.getList();
      });
    },

    update() {
      Edit(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    },
    create() {
      Create(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    }
  }
};
</script>

<style>
/* .table-container {
  margin: 20px 0;
} */
.alert-container {
  margin: 20px 0;
}
</style>
